<template>
  <el-popover trigger="click"
              :show-arrow="false"
              popper-class="v-color-picker-popper"
              :width="262"
              placement="bottom-end"
              :hide-after="1"
              :fallbackPlacements="['left-start', 'left', 'top-end']"
              v-model:visible="visible"
              :offset="2"
  >
    <template #reference>
      <div class="v-color-picker__trigger">
        <span class="v-color-picker__color" :class="{'set': colors}">
          <span class="v-color-picker__color-inner"
                :style="{backgroundColor: colors ? colors.hex8 : 'transparent' }"></span>
        </span>
      </div>
    </template>

    <sketch v-if="type==='sketch'" v-model:colors="val"></sketch>
    <div class="v-color-picker__op">
      <el-button size="mini" @click="onClear">清空</el-button>
      <el-button size="mini" type="primary" @click="onConfirm">确定</el-button>
    </div>
  </el-popover>
</template>

<script lang="ts">
import { ElPopover, ElButton } from 'element-pe'
import 'element-pe/es/components/popover/style/css'
import 'element-pe/es/components/button/style/css'
import Sketch from './Sketch.vue'
import { ref } from 'vue'
import { addRecentColor } from './useSketch'

export default {
  name: 'ColorPicker',
  components: { Sketch, ElPopover, ElButton },
  props: {
    type: {
      type: String,
      default: 'sketch',
    },
    colors: {
      type: Object,
    },
  },
  emits: ['update:colors'],
  setup(props: any, ctx: any) {
    const val = ref(props.colors)
    const visible = ref(false)

    return {
      val,
      visible,
      onClear() {
        ctx.emit('update:colors', null)
        visible.value = false
      },
      onConfirm() {
        addRecentColor(val.value.hex8)
        ctx.emit('update:colors', val.value)
        visible.value = false
      },
    }
  },
}
</script>